// Websocket Endpoint url
var host = window.location.host;
var path = window.location.pathname;
var webCtx = path.substring(0, path.indexOf('/', 1));
var endPointURL = "ws://" + window.location.host + webCtx + "/mudserver";


var chatClient = null;

function parse(msg)
{
	var renderer = $("#renderer").val(); 
	if (  renderer == "normal")
		return render_normal(msg);
	else if ( renderer == "reducido" )
		return render_reducido(msg);
	else if (renderer == "ampliado" )
		return render_ampliado(msg);

}

function connect () {
    chatClient = new WebSocket(endPointURL);
    chatClient.onmessage = function (event) {
    	
    	var jsonObj = JSON.parse(event.data);
    	var message = jsonObj.message;        
        var msgs = $("#messages"); 
    	msgs.append("<div>"+parse(message)+"</div>");
    	msgs[0].scrollTop = msgs[0].scrollHeight;
    };
}

function disconnect () {
    chatClient.close();
}

function sendMessage() {
    var user = document.getElementById("userName").value.trim();
    if (user === "")
    	return;        
    
    var inputElement = document.getElementById("messageInput");
    var message = inputElement.value.trim();
    if (message !== "") {
        var jsonObj = {"message" : message};
        chatClient.send(JSON.stringify(jsonObj));
        inputElement.value = "";
    }
    inputElement.focus();
}

function render_ampliado(msg)
{
	return msg;
}

function render_reducido(msg)
{
	return msg;
}

function render_normal(msg)
{
	return msg;
}
